<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import {
  getOrderList,
  exportOrderList,
  distributeOrder,
  getWorkList,
  finishOrder,
  getChannelList,
} from '@/api/order'
import { ElMessage } from 'element-plus'
import { formatTime, getFriendlyTime } from '@/utils/index'
const router = useRouter()

const form = ref({
  order_no: '',
  customer_name: '',
  customer_mobile: '',
  channel_name: '',
  address: '',
  created_time: '',
  start_time: '',
  end_time: '',
  status: [],
  worker_name: '',
  work_time: '',
  page: 1,
  page_size: 10,
  channel_id: '',
  work_time_start: '',
  work_time_end: '',
})

const formDialog = ref({
  worker_name: '',
  worker_phone: '',
  work_time: '',
  id: '',
  order_id: '',
})

const formRef = ref()
const total = ref(0)
const tableData = ref([])
const selectedRows = ref([])
const tableRef = ref()
const tableLoading = ref(false) // 表格加载状态

// 表单校验规则
const rules = {
  worker_name: [{ required: true, message: '请选择上门师傅', trigger: 'change' }],
  worker_phone: [{ required: true, message: '请输入师傅手机', trigger: 'blur' }],
  work_time: [{ required: true, message: '请选择上门时间', trigger: 'change' }],
}

onMounted(async () => {
  await getData()
  getWorkListData()
  getChannelListData()
})
const workList = ref([])

const getWorkListData = async () => {
  const res = await getWorkList({
    page: 1,
    page_size: 1000,
  })
  workList.value = res.data.list
}

const channelList = ref([])
const getChannelListData = async () => {
  const res = await getChannelList({
    page: 1,
    page_size: 1000
  })
  channelList.value = res.data.list
}

const getData = async () => {
  try {
    tableLoading.value = true // 开始加载
    if (form.value.created_time) {
      form.value.start_time = form.value.created_time[0]
      form.value.end_time = form.value.created_time[1]
    }

    // 上门时间范围处理
    if (form.value.work_time) {
      form.value.work_time_start = form.value.work_time[0]
      form.value.work_time_end = form.value.work_time[1]
    }

    // 处理多选状态，用逗号拼接
    const params = { ...form.value }
    if (Array.isArray(params.status) && params.status.length > 0) {
      params.status = params.status.join(',')
    }
    // 不传原始范围字段
    if (params.work_time) delete params.work_time

    const res = await getOrderList(params)
    tableData.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('获取订单列表失败:', error)
  } finally {
    tableLoading.value = false // 结束加载
  }
}

// 处理二进制响应
const handleBinaryResponse = (blob) => {
  // 检查 blob 是否有效
  if (!blob || blob.size === 0) {
    ElMessage.error('下载的文件为空')
    return
  }

  try {
    // 创建下载链接
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url

    // 设置文件名（可以从响应头获取或自定义）
    const filename = `订单列表_${new Date().toISOString().split('T')[0]}.xlsx`
    link.download = filename

    // 触发下载
    document.body.appendChild(link)
    link.click()

    // 清理
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)

    ElMessage.success('文件下载成功')
  } catch (error) {
    console.error('文件下载失败:', error)
    ElMessage.error('文件下载失败')
  }
}

const exportLoading = ref(false)

const exportExcel = async () => {
  if (exportLoading.value) return

  const params = {
    ...form.value,
    is_export: 1,
  }

  // 处理多选状态，用逗号拼接
  if (Array.isArray(params.status) && params.status.length > 0) {
    params.status = params.status.join(',')
  }

  console.log('导出参数:', params)

  try {
    exportLoading.value = true
    console.log('开始导出...')
    // 上门时间范围处理
    if (params.work_time) {
      params.work_time_start = params.work_time[0]
      params.work_time_end = params.work_time[1]
      delete params.work_time
    }
    const res = await exportOrderList(params)
    console.log('导出响应:', res)

    if (res instanceof Blob) {
      handleBinaryResponse(res)
    } else {
      console.error('导出响应不是 Blob 类型:', typeof res, res)
      ElMessage.error('导出失败：响应格式错误')
    }
  } catch (error) {
    console.error('导出失败:', error)
    console.error('错误详情:', {
      message: error.message,
      response: error.response,
      status: error.response?.status,
      data: error.response?.data,
    })
    ElMessage.error('导出失败')
  } finally {
    exportLoading.value = false
  }
}

// 查询
const onQuery = async () => {
  form.value.page = 1
  selectedRows.value = [] // 清空选择
  await getData()
}

// 重置
const onReset = async () => {
  form.value = {
    order_no: '',
    customer_name: '',
    customer_mobile: '',
    channel_name: '',
    address: '',
    created_time: '',
    start_time: '',
    end_time: '',
    channel_id: '',
    status: [],
    worker_name: '',
    work_time: '',
    page: 1,
    page_size: 10,
    work_time_start: '',
    work_time_end: '',
  }
  selectedRows.value = [] // 清空选择
  await getData()
}

// 分页事件
const handleSizeChange = async (val) => {
  form.value.page_size = val
  form.value.page = 1
  selectedRows.value = [] // 清空选择
  await getData()
}
const handleCurrentChange = async (val) => {
  form.value.page = val
  selectedRows.value = [] // 清空选择
  await getData()
}

const view = (id) => {
  router.push({
    name: 'ordersInfo',
    query: {
      id,
    },
  })
}

const dialogTitle = ref('派单')

const dialogFormVisible = ref(false)
const dialogFormVisible2 = ref(false)
const dialogFormVisible3 = ref(false)

// 是否有选中订单
const hasSelection = computed(() => selectedRows.value.length > 0)

// 表格选择变化处理
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
  console.log('=== 表格选择变化 ===')
  console.log('选中的订单数量:', rows.length)
  console.log('选中的订单详情:', rows)
  if (rows.length > 0) {
    console.log(
      '选中的订单ID列表:',
      rows.map((item) => item.id),
    )
    console.log(
      '选中的订单编号列表:',
      rows.map((item) => item.order_no),
    )
  }
}

const overOrder = () => {
  dialogFormVisible3.value = true
}

const overOrderOk = async () => {
  console.log('overOrderOk')
  const ids = selectedRows.value.map((item) => item.id).join(',')
  const params = {
    id: ids,
  }
  try {
    const res = await finishOrder(params)
    if (res.code == 200) {
      dialogFormVisible3.value = false
      selectedRows.value = [] // 清空选择
      await getData() // 刷新数据
      ElMessage.success('完成订单成功')
    }
  } catch (error) {
    console.error('完成订单失败:', error)
  }
}

const dispath = (row) => {
  dialogTitle.value = '派单'
  dialogFormVisible.value = true
  formDialog.value.id = row.id
  formDialog.value.order_id = row.id + ''
}

const dispathConfirm = () => {
  dialogTitle.value = '批量派单'
  dialogFormVisible.value = true
  dialogFormVisible2.value = false
}

const dispathOk = async () => {
  await formRef.value.validate()
  const worker = workList.value.find((item) => item.id === formDialog.value.worker_name)
  const worker_name = worker ? worker.work_name : formDialog.value.worker_name
  const params = {
    order_id: formDialog.value.order_id + '',
    worker_name: worker_name,
    worker_phone: formDialog.value.worker_phone,
    work_time: formDialog.value.work_time,
  }
  try {
    await distributeOrder(params)
    dialogFormVisible.value = false
    selectedRows.value = [] // 清空选择
    await getData() // 刷新数据
    ElMessage.success('派单成功')
  } catch (error) {
    console.error('派单失败:', error)
  }
}

const changeWork = (val) => {
  const item = workList.value.find((item) => item.id === val)
  if (item) {
    formDialog.value.worker_phone = item.work_phone
  }
}

const closeDialog = () => {
  formDialog.value.worker_name = ''
  formDialog.value.worker_phone = ''
  formDialog.value.work_time = ''
  formDialog.value.id = ''
  formDialog.value.order_id = ''
  formRef.value.resetFields()
}

const batchDispath = () => {
  dialogFormVisible2.value = true
  formDialog.value.order_id = selectedRows.value.map((item) => item.id).join(',')
}

const add = () => {
  router.push({
    name: 'ordersEdit',
    query: {
      type: 1,
    },
  })
}

const edit = (id) => {
  router.push({
    name: 'ordersEdit',
    query: {
      type: 2,
      id,
    },
  })
}

const handleTime = (val) => {
  console.log(123123)
  form.value.start_time = val[0]
  form.value.end_time = val[1]
  console.log(form, 'form', 'val', val)
}
const handleWorkTime = (val) => {
  form.value.work_time_start = val?.[0] || ''
  form.value.work_time_end = val?.[1] || ''
}
const handleStaus = (status) => {
  status = status.toString()
  switch (status) {
    case '1':
      return '待付款'
      break
    case '2':
      return '待上门'
      break
    case '3':
      return '服务中'
      break
    case '4':
      return '已完成'
      break
    case '5':
      return '已取消'
      break
    case '6':
      return '退款中'
      break
    case '7':
      return '已退款'
      break
    case '8':
      return '退款失败'
      break
    default:
      return '-'
      break
  }
}

const handleTyle = (status) => {
  status = status.toString()
  switch (status) {
    case '1':
      return 'danger'
      break
    case '2':
      return 'primary'
      break
    case '3':
      return 'success'
      break
    case '4':
      return 'warning'
      break
    case '5':
      return 'info'
      break
    case '6':
      return 'info'
      break
    case '7':
      return 'info'
      break
    case '8':
      return 'info'
      break
    default:
      return ''
      break
  }
}
// 状态切换处理
const handleStatusChange = async () => {
  selectedRows.value = [] // 清空选择
  await getData()
}
</script>
<template>
  <div class="main">
    <el-form :inline="true" :model="form" class="demo-form-inline">
      <el-form-item label="订单编号:">
        <el-input
          v-model="form.order_no"
          placeholder="请输入订单编号"
          clearable
          style="width: 185px"
        />
      </el-form-item>
      <el-form-item label="客户姓名:">
        <el-input
          v-model="form.customer_name"
          placeholder="请输入客户姓名"
          clearable
          style="width: 185px"
        />
      </el-form-item>
      <el-form-item label="客户手机:">
        <el-input
          v-model="form.customer_mobile"
          placeholder="请输入客户手机"
          clearable
          style="width: 185px"
        />
      </el-form-item>
      <el-form-item label="渠道来源:">
        <el-select
          v-model="form.channel_id"
          placeholder="请选择渠道来源"
          style="width: 185px"
          clearable
        >
          <el-option :label="item.name" :value="item.id" :key="item.id" v-for="item in channelList" />
        </el-select>
      </el-form-item>
      <el-form-item label="服务地址:">
        <el-input
          v-model="form.address"
          placeholder="请输入服务地址"
          clearable
          style="width: 185px"
        />
      </el-form-item>
      <el-form-item label="下单时间:">
        <el-date-picker
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          placeholder="请选择下单时间"
          style="width: 185px"
          format="YYYY-MM-DD HH:mm:ss"
          v-model="form.created_time"
          date-format="YYYY/MM/DD ddd"
          time-format="A hh:mm:ss"
          @change="handleTime"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item label="订单状态:">
        <!-- 1:待付款 2:待上门 3:服务中 4:已完成 5:已取消 -->
        <el-select
          v-model="form.status"
          placeholder="请选择订单状态"
          style="width: 185px"
          multiple
          collapse-tags
          collapse-tags-tooltip
          clearable
        >
          <el-option label="待付款" value="1" />
          <el-option label="待上门" value="2" />
          <el-option label="服务中" value="3" />
          <el-option label="已完成" value="4" />
          <el-option label="已取消" value="5" />
          <el-option label="退款中" value="6" />
          <el-option label="已退款" value="7" />
        </el-select>
      </el-form-item>
      <el-form-item label="上门师傅:">
        <el-input
          v-model="form.worker_name"
          placeholder="请输入上门师傅"
          clearable
          style="width: 185px"
        />
      </el-form-item>
      <el-form-item label="上门时间:">
        <el-date-picker
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          placeholder="请选择上门时间"
          style="width: 185px"
          format="YYYY-MM-DD HH:mm:ss"
          v-model="form.work_time"
          date-format="YYYY/MM/DD ddd"
          time-format="A hh:mm:ss"
          @change="handleWorkTime"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onQuery">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button @click="onReset">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="actions-btn">
      <el-button type="primary" @click="add">新增</el-button>
      <el-button type="success" :disabled="!hasSelection" @click="batchDispath">
        批量派单
        <!-- <span v-if="hasSelection" class="selection-count">({{ selectedRows.length }})</span> -->
      </el-button>
      <el-button type="warning" :disabled="!hasSelection" @click="overOrder">完成订单</el-button>
      <span style="margin-left: 40px">
        <el-button @click="exportExcel" :loading="exportLoading">导出</el-button>
      </span>
    </div>

    <div class="tab">
      <el-radio-group v-model="form.status" @change="handleStatusChange">
        <!-- 1:待付款 2:待上门 3:服务中 4:已完成 5:已取消 7:已退款 -->
        <el-radio-button label="待付款" value="1" />
        <el-radio-button label="待上门" value="2" />
        <el-radio-button label="服务中" value="3" />
        <el-radio-button label="已完成" value="4" />
        <el-radio-button label="已取消" value="5" />
        <el-radio-button label="已退款" value="7" />
        <el-radio-button label="全部" value="" />
      </el-radio-group>
    </div>
    <el-table
      ref="tableRef"
      :data="tableData"
      border
      style="height: 500px"
      :cell-style="{ textAlign: 'center' }"
      :header-cell-style="{ 'text-align': 'center' }"
      @selection-change="handleSelectionChange"
      v-loading="tableLoading"
      element-loading-spinner="el-icon-loading"
    >
      <el-table-column type="selection" width="50" />
      <el-table-column prop="order_no" label="订单编号" width="170">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="view(scope.row.id)">
            {{ scope.row.order_no }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column prop="customer_name" label="客户姓名" width="150" show-overflow-tooltip />
      <el-table-column prop="customer_mobile" label="客户手机" width="150" show-overflow-tooltip />
      <el-table-column prop="address" label="服务地址" width="210" show-overflow-tooltip />
      <el-table-column prop="goods_name" label="服务内容" width="150" show-overflow-tooltip />
      <el-table-column prop="created_at" label="下单时间" width="180" show-overflow-tooltip>
        <template #default="scope">
          {{ formatTime(scope.row.created_at) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="订单状态" width="100" show-overflow-tooltip>
        <template #default="scope">
          <el-button
            link
            :style="scope.row.status == '4' ? 'color: #F59A23' : ''"
            :type="handleTyle(scope.row.status)"
            size="small"
          >
            {{ handleStaus(scope.row.status) }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column prop="subscribe_time" label="预约时间" width="180" show-overflow-tooltip>
        <template #default="scope">
          {{ formatTime(scope.row.subscribe_time) }}
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="订单备注" width="180" show-overflow-tooltip />
      <el-table-column label="订单渠道" width="180">
        <template #default="scope">
          {{ scope.row.channel_name ? scope.row.channel_name : '-' }}
        </template>
      </el-table-column>
      <el-table-column label="上门师傅" width="100" show-overflow-tooltip>
        <template #default="scope">
          {{ scope.row.worker_name ? scope.row.worker_name : '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="work_time" label="上门时间" width="180">
        <template #default="scope">
          {{ scope.row.work_time ? formatTime(scope.row.work_time) : '-' }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="150">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="view(scope.row.id)">查看</el-button>
          <el-button link type="danger" size="small" @click="edit(scope.row.id)">修改</el-button>
          <el-button
            link
            type="success"
            size="small"
            @click="dispath(scope.row)"
            :disabled="
              scope.row.status == '1' || scope.row.status == '4' || scope.row.status == '5'
            "
            >派单</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="form.page"
        v-model:page-size="form.page_size"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="500" @close="closeDialog">
      <el-form :model="formDialog" :rules="rules" ref="formRef">
        <el-form-item label="上门师傅" :label-width="100" prop="worker_name">
          <el-select
            v-model="formDialog.worker_name"
            placeholder="请选择上门师傅"
            style="width: 200px"
            @change="changeWork"
            allow-create
            clearable
            filterable
          >
            <el-option
              v-for="item in workList"
              :key="item.id"
              :label="item.work_name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="师傅手机" :label-width="100" prop="worker_phone">
          <el-input
            v-model="formDialog.worker_phone"
            autocomplete="off"
            placeholder="请输入师傅手机"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="上门时间" :label-width="100" prop="work_time">
          <el-date-picker
            v-model="formDialog.work_time"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择上门时间"
          />
        </el-form-item>
        <el-form-item :label-width="30">
          <div class="tips">注意：派单量应考虑师傅当天的承单量 和师傅当天的综合收入。</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">关闭</el-button>
          <el-button type="primary" @click="dispathOk"> 派单 </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="dialogFormVisible2" title="批量派单" width="500">
      <div class="info">
        确认
        <span>【批量派单】</span>
        已选中的<span class="count">{{ selectedRows.length }}</span
        >个订单吗？
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible2 = false">关闭</el-button>
          <el-button type="primary" @click="dispathConfirm"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="dialogFormVisible3" title="完成订单" width="500">
      <div class="info">
        确认
        <span>【完成订单】</span>
        已选中的<span class="count">{{ selectedRows.length }}</span
        >个订单吗？
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible3 = false">关闭</el-button>
          <el-button type="primary" @click="overOrderOk"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<style scoped lang="scss">
.main {
  .tab {
    margin-bottom: 20px;
  }
}

.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
.actions-btn {
  margin-bottom: 20px;
}
.pagination {
  margin: 20px auto;
  display: flex;
  justify-content: center;
}
.tips {
  color: red;
  font-size: 12px;
}
.info span {
  color: #e6a23c;
}
</style>
